package com.lottery.pay.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.entity.PaymentRecords;
import com.lottery.common.service.OrderInfoService;
import com.lottery.common.utils.DateUtil;
import com.lottery.pay.Constants.WeixinConstant;
import com.lottery.pay.Utils.XMLUtils;
import com.lottery.pay.Utils.wxUtil.MainUtil;
import com.lottery.pay.Utils.wxUtil.UserInfo;
import com.lottery.pay.service.PaymentRecordsService;
import com.lottery.pay.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.soap.Addressing;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Service
public class WeixinServiceImpl implements WeixinService {
    private ReQueryResult result = new ReQueryResult();

    @Resource
    private PaymentRecordsService recordsService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Override
    public ReQueryResult getOpenId(String code, String state,HttpSession session) {
        String app_id = WeixinConstant.APP_ID;
        String app_secret = WeixinConstant.APP_SECRET;
        UserInfo userInfo = new UserInfo();
        String openId = userInfo.getOpenId(app_id, app_secret, code);
        log.info("openId is {} ",openId);
//        if (!StringUtils.isEmpty(openId))
//            redisTemplate.opsForValue().set("openId",openId);
        session.setAttribute("openId",openId);

        result.success(Constants.SUCCESS_DESC);
        return result;
    }


    @Override
    public ReQueryResult createPayment(PaymentRecords records)  {
        log.info("WxController place in");

        String payType="";
        if (records.getPayType()==1) {
            payType="APP";
        }
        if (records.getPayType()==2) {
            payType="MWEB";
        }
        if (records.getPayType()==4) {
            payType="JSAPI";
        }
        if (records.getPayType()==6) {
            payType="NATIVE";
        }
//        records.setTotalFee(new BigDecimal(records.getTotalFee()).multiply(new BigDecimal("100")).intValue());
        records.setTotalFee(new BigDecimal("1"));
        Object paymentParam = paymentService.payoff(records.getBody(),records.getOrderNum(),records.getTotalFee().intValue(), records.getOpenId(),records.getIp(),payType);
        log.info(JSON.toJSONString(paymentParam));
        result.success(Constants.SUCCESS_DESC);
        result.setData(paymentParam);
        return result;
    }

    @Override
    public ReQueryResult queryPayment(PaymentRecords records){
        return null;
    }

    @Override
    public ReQueryResult refundPayment(PaymentRecords records) {
        return null;
    }

    @Override
    public ReQueryResult queryRefundPayment(PaymentRecords records) {
        return null;
    }

    @Override
    public ReQueryResult closePayment(PaymentRecords records) {
        return null;
    }

    @Override
    public ReQueryResult resultDispose( HttpServletRequest request) {
        result = new ReQueryResult();
        log.info("------------ order result --------------");
        String inputLine;
        String notityXml = "";
        NutMap nutMap=new NutMap();
        //微信给返回的东西
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
            result.error(" PAYOFF_RETURN_MSG_ERROR ");
            log.error(e.toString());
            return result;
        }
        if (StringUtils.isEmpty(notityXml)) {
            log.error(" PAYOFF_RETURN_MSG_ERROR ");
            result.error(" PAYOFF_RETURN_MSG_ERROR ");
            return result;
        }
        log.info(notityXml);
        //已修改从xmlString中获取对象 后续可精简代码
        Map<String,Object> map = XMLUtils.xmlString2Map(notityXml);
        log.info("result map is {}",JSON.toJSONString(map));
        String wxSign=map.get("sign").toString();
        // object转化为TreeMap
        TreeMap<Object, Object> treeMap2 = MainUtil.objectToTreeMap(map);

        // 生成签名
        String sign = MainUtil.creatSign(treeMap2,  WeixinConstant.API_KEY);
        log.info("mySign is {}  and wxSign is {}",sign,wxSign);
//        if (!sign.equals(wxSign)){
//            log.error(" 验签失败 ");
//            result.error(" 验签失败 ");
//            return result;
//        }
        Integer status=3;//失败
        if (map.get("result_code")!=null&&"SUCCESS".equals(map.get("result_code").toString()))
            status=0;//成功

        PaymentRecords records=new PaymentRecords(map.get("out_trade_no").toString(),map.get("transaction_id").toString(),
                DateUtil.StringToDateTime(map.get("time_end").toString()),map.get("return_code").toString(),
                map.get("err_code")==null?"":map.get("err_code").toString(),
                map.get("err_code_des")==null?"":map.get("err_code_des").toString());
        records.setStatus(status);
        Integer count=recordsService.updateByPrimaryKeySelective(records);
        if (count==0){
            log.error(" 支付订单更新失败 ");
            result.error("支付订单更新失败");
            return result;
        }
        Boolean flag=false;
        log.info("outTradeNo is {}",records.getOrderNum());
        //业务流程
        try {
            flag=true;
            log.info("wxBackInfo records is {}",JSON.toJSONString(records));
            records.setType(Constants.TYPE_TWO);
            result=orderInfoService.synthesizeOrder(records);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(ExceptionUtils.getFullStackTrace(e));
            result.error("订单更新失败");
            return result;
        }
        log.info("flag is {} ",flag);
        result.success(Constants.SUCCESS_DESC);
        return result;
    }


    /**
     * 得到本地机器的IP
     * @return
     */
    public static String getHostIp(){
        String ip = "";
        try{
            ip = InetAddress.getLocalHost().getHostAddress();
        }catch(UnknownHostException e){
            e.printStackTrace();
        }
        return ip;
    }


}
